import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class InputSystem {
    public static List<Token> readFile(String fileName) throws IOException {
        File file = null;
        // 绝对路径处理
        if(fileName.indexOf('/') != -1 || fileName.indexOf('\\') != -1){
            file = new File(fileName);
        }
        else{
            // 拼接文件路径
            File dir = new File("./02-lex-simple/src");
            file = new File(dir.getCanonicalPath() + File.separator + fileName);
        }

        // 创建流
        FileInputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
        BufferedReader br = new BufferedReader(isr);

        // 按行读取文件
        int row = 0;
        String line = "";
        List<Token> tokenList = new ArrayList<>();
        while ((line = br.readLine()) != null) {
            row++;
            List<Token> tokens = LexParser.parser(line, row, file.getPath());
            if(tokens == null) return null;
            tokenList.addAll(tokens);
        }
        // 关闭流
        br.close();
        isr.close();
        fis.close();
        return tokenList;
    }

    public static void printTokenInfo(List<Token> tokenList){
        if(tokenList == null) return;
        tokenList.forEach((token)->{
            System.out.format("{%d,%s,%s,line %d,column(%d,%d)}\n",
                    token.getTokenType().getSpeciesCode(),token.getTokenType(),token.getWord(),token.getRow(),token.getBeginCol(),token.getEndCol());
        });
    }
}
